package com.servlet;

import com.dao.EmailDao;
import com.dao.UserDao;
import com.dao.implement.EmailDaoImpl;
import com.dao.implement.UserDaoImpl;
import com.model.Action;
import com.model.Email;
import com.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.List;

/**
 * @author Wray
 */
@WebServlet("/EmailServlet")
public class EmailServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private UserDao dao = new UserDaoImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String act =request.getParameter("act");
        if(act!=null){
            //根据传输的act调用不同的方法进行处理
            switch (act) {
                case "sendEmail":
                    insertEmail(request,response);
                    break;
                case "send":
                    sendUser(request,response);
                    break;
                case "displayInbox":
                    selectByReceiver(request,response);
                    break;
                case "displayOutbox":
                    selectBySender(request,response);
                    break;
////                case "insert"::

////                    insertUser(request,response);
////                    break;
//                case "update":
//                    updateUser(request, response);
//                    break;
                    case "deleteBySender":
                        deleteBySender(request, response);
                        break;
                case "deleteByReceiver":
                    deleteByReceiver(request, response);
                    break;
                  default:insertEmail(request,response);
                    break;
            }
        }else {
            response.getWriter().print("act参数不能位空，请检查是否传输了该参数！");
        }

    }



    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    private void deleteByReceiver(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        Integer emailId= Integer.valueOf(request.getParameter("emailId"));
        new EmailDaoImpl().deleteEmail(emailId,Action.RECEIVER);
        response.sendRedirect("EmailServlet?act=displayInbox&username="+request.getParameter("username"));
    }
    private void deleteBySender(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        Integer emailId= Integer.valueOf(request.getParameter("emailId"));
        new EmailDaoImpl().deleteEmail(emailId,Action.SENDER);

        response.sendRedirect("EmailServlet?act=displayOutbox&username="+request.getParameter("username"));
    }
    private void selectBySender(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        String username =  request.getParameter("username");
        //String username="111";
        List<Email>emailList=new EmailDaoImpl().selectByUser(username,Action.SENDER);
        request.setAttribute("emailList",emailList);
        request.setAttribute("username",username);
        request.getRequestDispatcher("pages/emailmgr/outbox.jsp").forward(request,response);
    }

    private void selectByReceiver(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
         String username =  request.getParameter("username");
        //String username="111";
        List<Email>emailList=new EmailDaoImpl().selectByUser(username,Action.RECEIVER);
        request.setAttribute("emailList",emailList);
        request.setAttribute("username",username);
        request.getRequestDispatcher("pages/emailmgr/inbox.jsp").forward(request,response);
    }
    private void sendUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = (String)request.getSession().getAttribute("username");
        User user = dao.selectByUsername(username);
        request.setAttribute("user", user);
        request.getRequestDispatcher("pages/emailmgr/send.jsp").forward(request, response);
    }
    private void insertEmail(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        User sender = (User) request.getSession().getAttribute("user");
        String receivername = request.getParameter("receivername");
        String title = request.getParameter("title");
        String text = request.getParameter("text");
        User receiver=new UserDaoImpl().selectByUsername(receivername);
        //第二次密码
        //trim判断是否有空格
        if(receivername==null||receivername.trim().isEmpty()){
            request.setAttribute("receiverError", "收件人不能为空");
            request.getRequestDispatcher("pages/emailmgr/send.jsp").forward(request, response);
            return;
        }
        if(receiver==null){
            request.setAttribute("receiverError", "收件人不存在");
            request.getRequestDispatcher("pages/emailmgr/send.jsp").forward(request, response);
            return;
        }
        if(receivername.equals(sender.getUsername())){
            request.setAttribute("receiverError", "收件人不能为自己");
            request.getRequestDispatcher("pages/emailmgr/send.jsp").forward(request, response);
            return;
        }

        if(title==null||title.trim().isEmpty()){
            request.setAttribute("titleError", "标题不能为空");
            request.getRequestDispatcher("pages/emailmgr/send.jsp").forward(request, response);
            return;
        }
        if(text==null||text.trim().isEmpty()){
            request.setAttribute("textError", "文章不能为空");
            request.getRequestDispatcher("pages/emailmgr/send.jsp").forward(request, response);
            return;
        }
        Timestamp time = new Timestamp(System.currentTimeMillis());
        PrintWriter out=response.getWriter();
        EmailDao emailDao=new EmailDaoImpl();
        Email email=new Email(sender.getUsername(),receivername,title,text,time, Action.BOTH_EXIST);
        if(emailDao.insertEmail(email)){
            request.getSession().setAttribute("resultMSG","发送成功");
            request.getRequestDispatcher("pages/emailmgr/send.jsp").forward(request, response);
        }else {
            request.getSession().setAttribute("resultMSG","发送失败，发生未知错误");
            request.getRequestDispatcher("pages/emailmgr/send.jsp").forward(request, response);
        }
    }
}
